package com.sugar.follow.up.module.business.service.tag;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import com.sugar.follow.up.module.business.controller.admin.tag.vo.*;
import com.sugar.follow.up.module.business.dal.dataobject.tag.TagDO;
import com.sugar.follow.up.framework.common.pojo.PageResult;
import com.sugar.follow.up.framework.common.pojo.PageParam;
import com.sugar.follow.up.framework.common.util.object.BeanUtils;

import com.sugar.follow.up.module.business.dal.mysql.tag.TagMapper;

import static com.sugar.follow.up.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.follow.up.framework.common.util.collection.CollectionUtils.convertList;
import static com.sugar.follow.up.framework.common.util.collection.CollectionUtils.diffList;
import static com.sugar.follow.up.module.business.enums.ErrorCodeConstants.*;

/**
 * 标签 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class TagServiceImpl implements TagService {

    @Resource
    private TagMapper tagMapper;

    @Override
    public Long createTag(TagSaveReqVO createReqVO) {
        // 插入
        TagDO tag = BeanUtils.toBean(createReqVO, TagDO.class);
        tagMapper.insert(tag);

        // 返回
        return tag.getId();
    }

    @Override
    public void updateTag(TagSaveReqVO updateReqVO) {
        // 校验存在
        validateTagExists(updateReqVO.getId());
        // 更新
        TagDO updateObj = BeanUtils.toBean(updateReqVO, TagDO.class);
        tagMapper.updateById(updateObj);
    }

    @Override
    public void deleteTag(Long id) {
        // 校验存在
        validateTagExists(id);
        // 删除
        tagMapper.deleteById(id);
    }

    @Override
        public void deleteTagListByIds(List<Long> ids) {
        // 删除
        tagMapper.deleteByIds(ids);
        }


    private void validateTagExists(Long id) {
        if (tagMapper.selectById(id) == null) {
            throw exception(TAG_NOT_EXISTS);
        }
    }

    @Override
    public TagDO getTag(Long id) {
        return tagMapper.selectById(id);
    }

    @Override
    public PageResult<TagDO> getTagPage(TagPageReqVO pageReqVO) {
        return tagMapper.selectPage(pageReqVO);
    }

    @Override
    public List<TagTreeRespVO> getTagTree() {
        List<TagDO> tags = tagMapper.selectList();
        return BeanUtils.toBean(tags, TagTreeRespVO.class,
                o -> o.setValue(o.getTitle()).setLabel(o.getTitle())
                        .setChildren(o.getContent()
                                .stream()
                                .map(c -> new TagTreeRespVO().setLabel(c).setValue(c))
                                .collect(Collectors.toList())));
    }
}